package com.sena.engine.snmp.handler;

import com.sena.engine.common.exception.SenaSnmpRunTimeException;
import com.sena.engine.snmp.utils.SnmpUtils;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpObjectType;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

import java.util.Vector;

/**
 * 更新操作
 */

/**
 * @author Admin
 */
public class UpdateHandler {
    /**
     * 更新mib数据
     *
     * @param object
     * @param snmp
     * @param target
     * @throws SenaSnmpRunTimeException
     */
    public void update(Object object, Snmp snmp, Target target) throws SenaSnmpRunTimeException {
        try {
            String oid = SnmpUtils.getMibOIDofClass(object.getClass());
            MibValueSymbol mibValueSymbol = SnmpUtils.getMibSymbolByOid(oid);
            String indexOID = SnmpUtils.getTableOrGroupIndexOID(object, mibValueSymbol);
            Class clazz = object.getClass();
            Vector vector = SnmpUtils.getWritedFieldsInMibNode(clazz, mibValueSymbol);
            PDU pdu = SnmpUtils.createPdu(target.getVersion());
            for (int i = 0; i < vector.size(); i++) {
                MibValueSymbol symbol = (MibValueSymbol) vector.get(i);
                String OID = symbol.getValue().toString();
                String nodeOID = OID + "." + indexOID;
                String oidName = mibValueSymbol.getMib().getSymbolByOid(OID).getName();
                SnmpObjectType snmpObjectType = (SnmpObjectType) symbol.getType();
                Variable var15 = SnmpUtils.getFieldValue(object, oidName, snmpObjectType.getSyntax());
                pdu.add(new VariableBinding(new OID(nodeOID), var15));
            }
            ResponseEvent event = snmp.set(pdu, target);
            SnmpUtils.checkSnmpError(event);
        } catch (Exception e) {
            String msg = "把对象数据写入到设备snmp中出错,对象:" + object.getClass().getName() + ",设备ip:" + target.getAddress() + ",错误:" + e.getMessage();
            throw new SenaSnmpRunTimeException(msg);
        }
    }
}
